package com.itheima.ai.controller.v1;

import com.itheima.ai.service.ChatService;
import com.itheima.model.ai.dtos.ChatRequest;
import com.itheima.model.ai.dtos.ChatResponse;
import com.itheima.model.ai.pojos.ChatMessage;
import com.itheima.model.ai.pojos.ChatSession;
import com.itheima.model.common.dtos.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/v1/ai/chat")
public class ChatController {
    
    @Autowired
    private ChatService chatService;
    
    /**
     * 发送消息
     */
    @PostMapping("/send")
    public ResponseResult<ChatResponse> sendMessage(@RequestBody ChatRequest request) {
        try {
            ChatResponse response = chatService.sendMessage(request);
            return ResponseResult.okResult(response);
        } catch (Exception e) {
            log.error("发送消息失败", e);
            return ResponseResult.errorResult(500, e.getMessage());
        }
    }
    
    /**
     * 发送消息（流式响应）
     */
    @PostMapping(value = "/send/stream", produces = "text/event-stream;charset=UTF-8")
    public Flux<String> sendMessageStream(@RequestBody ChatRequest request) {
        log.info("收到流式请求: userId={}, message={}", request.getUserId(), request.getMessage());
        return chatService.sendMessageStream(request);
    }
    
    /**
     * 获取会话历史
     */
    @GetMapping("/history/{sessionId}")
    public ResponseResult<List<ChatMessage>> getHistory(
            @PathVariable String sessionId,
            @RequestParam Long userId) {
        try {
            List<ChatMessage> messages = chatService.getSessionMessages(userId, sessionId);
            return ResponseResult.okResult(messages);
        } catch (Exception e) {
            log.error("获取历史消息失败", e);
            return ResponseResult.errorResult(500, e.getMessage());
        }
    }
    
    /**
     * 清除会话
     */
    @DeleteMapping("/clear/{sessionId}")
    public ResponseResult<String> clearSession(
            @PathVariable String sessionId,
            @RequestParam Long userId) {
        try {
            chatService.clearSession(userId, sessionId);
            return ResponseResult.okResult("会话已清除");
        } catch (Exception e) {
            log.error("清除会话失败", e);
            return ResponseResult.errorResult(500, e.getMessage());
        }
    }
    
    /**
     * 获取用户的会话列表
     */
    @GetMapping("/sessions")
    public ResponseResult<List<ChatSession>> getSessions(@RequestParam Long userId) {
        try {
            List<ChatSession> sessions = chatService.getUserSessions(userId);
            return ResponseResult.okResult(sessions);
        } catch (Exception e) {
            log.error("获取会话列表失败", e);
            return ResponseResult.errorResult(500, e.getMessage());
        }
    }
    
    /**
     * 创建新会话
     */
    @PostMapping("/session")
    public ResponseResult<ChatSession> createSession(
            @RequestParam Long userId,
            @RequestParam(required = false) String title) {
        try {
            ChatSession session = chatService.createSession(userId, title);
            return ResponseResult.okResult(session);
        } catch (Exception e) {
            log.error("创建会话失败", e);
            return ResponseResult.errorResult(500, e.getMessage());
        }
    }
}

